package com.syt.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syt.enums.AuthStatusEnum;
import com.syt.exception.SYTException;
import com.syt.helper.JwtHelper;
import com.syt.model.user.Patient;
import com.syt.model.user.UserInfo;
import com.syt.result.ResultCodeEnum;
import com.syt.user.mapper.UserInfoMapper;
import com.syt.user.service.PatientService;
import com.syt.user.service.UserInfoService;
import com.syt.vo.user.LoginVo;
import com.syt.vo.user.UserAuthVo;
import com.syt.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xx
 * @since 2023-02-20
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PatientService patientService;

    /**
     * 认证审批 根据用户id修改认证审批状态
     * @param userId
     * @param authStatus
     * @return
     */
    @Transactional
    @Override
    public boolean updateAuthStatusByUserId(Long userId, Integer authStatus) {
        int i=0;
        if(authStatus.intValue()!=-1||authStatus.intValue()!=2){
           UserInfo userInfo = baseMapper.selectById(userId);
           userInfo.setAuthStatus(authStatus);
          i= baseMapper.updateById(userInfo);
       }
        if (i==1){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 根据用户id查询用户详情
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> getUserDetailsById(Long userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        //用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo", userInfo);
        //就诊人信息
        List<Patient> patientList = patientService.findPatientAllByUserId(userId);
        map.put("patientList", patientList);
        return map;
    }

    /**
     * 用户是否锁定状态
     *
     * @param userId
     * @param status
     */
    @Transactional
    @Override
    public boolean updateUserLockStatusByUserId(Long userId, Integer status) {

        if (status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            int i = baseMapper.updateById(userInfo);
            if (i == 1) {
                return true;
            }
        }
        return false;
    }

    /**
     * 用户列表(带条件分页)
     *
     * @param pageParam
     * @param userInfoQueryVo
     * @return
     */
    @Override
    public Page<UserInfo> selectUserInfoPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {

        String name = userInfoQueryVo.getKeyword();//用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();//认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间
        //判断条件是否为空
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.like("status", status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.like("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }
        //调用
        Page<UserInfo> infoPage = baseMapper.selectPage(pageParam, wrapper);
        //遍历封装
        infoPage.getRecords().stream().forEach(userInfo -> {
            this.packageUserInfo(userInfo);
        });


        return infoPage;
    }


    //遍历封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态
        String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        return userInfo;
    }

    /**
     * 用户认证接口
     *
     * @param userId
     * @param userAuthVo
     */
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    /**
     * 根据微信openid判断是否存在
     *
     * @param openId
     * @return
     */
    @Override
    public UserInfo selectWxInfoByOpenId(String openId) {
        //根据openid判断当前手机号码是否存在
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openId);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        if (userInfo != null) {
            return userInfo;
        }
        return null;
    }

    /**
     * 根据用户手机号码登录
     *
     * @param loginVo
     * @return
     */
    @Transactional
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从loginVo获取输入的手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new SYTException(ResultCodeEnum.PARAM_ERROR);
        }

        //判断手机验证码和输入验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            throw new SYTException(ResultCodeEnum.CODE_ERROR);
        }

        //判断手机号码
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.selectWxInfoByOpenId(loginVo.getOpenid());
            if (userInfo != null) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new SYTException(ResultCodeEnum.DATA_ERROR);
            }
        }

        //如果userInf为空，进行正常手机登录
        if (userInfo == null) {
            //判断是否第一次登录：根据手机号码查询数据库，如果不存在相同手机号就是第一次登录
            QueryWrapper<UserInfo> wrapper = new QueryWrapper();
            wrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setName(" ");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }


        //校验手机号码是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new SYTException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        //不是第一次登录，直接登录


        //返回登录信息
        //返回登录用户名
        //返回token信息
        Map<String, Object> map = new HashMap<String, Object>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            phone = userInfo.getPhone();
        }
        map.put("name", name);
        //使用jwt生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }
}
